from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
import base64, json
from ..models import Record,DlzUserInfo
from django.views.decorators.csrf import csrf_exempt
from urllib.parse import urlencode
import threading
import datetime
from loguru import logger
from .mq_utils.producer_example import send_msg_to_mq

logger.add("vot_spider.log")

@require_http_methods(["GET"])
def record(request):
    params = request.GET
    pstr = ""
    for k in params:
        pstr = k
        break
    base64_decoded  =  base64.urlsafe_b64decode(pstr)
    # print(get_ip(request))
    params = json.loads(base64_decoded)
    params['uip'] = get_ip(request)
    thread = threading.Thread(target=long_running_task, args=(params, request))
    thread.start()
    thread = threading.Thread(target=send_msg_to_mq, args=(params,))
    thread.start()
    # 立即返回，任务在thread中继续执行
    return HttpResponse("window", content_type="application/javascript; charset=utf-8")


@require_http_methods(["POST"])
@csrf_exempt
def record_post(request):
    logger.info(f"进来了")
    params = request.body
    params = json.loads(params)

    pstr = params["param"]
    logger.info(f"pstr: {pstr} - status|200")
    base64_decoded  =  base64.urlsafe_b64decode(pstr)
    # print(get_ip(request))
    print(base64_decoded)
    logger.info(f"base64_decoded for {base64_decoded} - status|200")
    params = json.loads(base64_decoded)
    params['uip'] = get_ip(request)
    print(get_ip(request))
    logger.info(f"ip for {get_ip(request)} - status|200")
    thread = threading.Thread(target=long_running_task, args=(params, request))
    thread.start()
    thread = threading.Thread(target=send_msg_to_mq, args=(params,))
    thread.start()
    # 立即返回，任务在thread中继续执行
    return HttpResponse("window", content_type="application/javascript; charset=utf-8")



def long_running_task(params={}, request=None):
    Record.objects.create(
        uip=params.get("ip"), 
        sip=params['uip'],
        url=params.get("url"), 
        evname=params.get("e"), 
        ua=params.get("ua"),
        target= params.get("tg"),
        content= params.get("c") if params.get("c") else request.META.get('HTTP_X_FORWARDED_FOR'),
        host= params.get("st"),

        uid=params.get("spid") if params.get("spid") else (params.get("uid") if params.get("uid") else "no_usr_key"), 
        page=params.get('pg'),
        pos = (params.get("x") if params.get("x") else "0") + "/" + (params.get("y") if params.get("y") else "0"),
    )

    # sleep(3)
    try:
        DlzUserInfo.objects.create(
            site=params.get("st"),
            uid=params.get("spid") if params.get("spid") else (
                params.get("uid") if params.get("uid") else "no_usr_key"),
        )
    except Exception as e:
        print("保存失败")
    print(params.get('ip'))
    pass

def get_ip(request):
    ip = request.GET.get("ip", "")
    if not ip:
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 多次反向代理后会有多个ip值，第一个ip才是真实ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 这里获得代理ip
    return ip
